package com.karry.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.karry.mapper.RecordMapper;
import com.karry.mapper.UserMapper;
import com.karry.pojo.Blog;
import com.karry.pojo.User;
import com.karry.service.UserService;
import com.karry.util.Page;
import com.karry.util.SqlSessionFactoryUtils;
import com.karry.util.XssStrUtils;
import com.karry.vo.ResultInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.util.ArrayList;

public class UserServiceImpl implements UserService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public ResultInfo<User> userSearchByNameAndPwd(String name, String pwd) {
        ResultInfo<User> resultInfo = new ResultInfo<>();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //密码加密
        pwd = DigestUtil.md5Hex(pwd);
        System.out.println("pwd:" + pwd);
        User user = mapper.userSearchBYNameAndPwd(name, pwd);
        System.out.println(user);
        //回收资源
        sqlSession.close();

        resultInfo.setResult(user);
        if (user == null){
            //账号不存在
            resultInfo.setCode(0);
            resultInfo.setMsg("账号或者密码错误");
        }else {
            resultInfo.setCode(1);
            resultInfo.setMsg("登陆成功");
        }
        return resultInfo;
    }

    @Override
    public ResultInfo<User> userRegister(String userName, String userPwd, String userEmail) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        //判断账号是否存在
        User user = mapper.userSearchByName(userName);
        //判断邮箱是否存在
        User u = mapper.userSearchByEmail(userEmail);
        if (user == null && u == null){
            //账号不存在，可以注册
            //构造昵称
            String nick = "新用户__" + userName;
            //密码加密
            userPwd = DigestUtil.md5Hex(userPwd);
            //获取user对象
            u = new User();
            u.setEmail(userEmail);
            u.setName(userName);
            u.setNick(nick);
            u.setPwd(userPwd);

            int res = mapper.userInsert(u);
            System.out.println("修改行数:" + res + "  新增主键值：" + u.getId());
            //获取账户
            resultInfo.setResult(mapper.userSearchBYNameAndPwd(userName, userPwd));
            resultInfo.setCode(res);
            if (res > 0){
                resultInfo.setMsg("注册成功");
                //记录
                record.insertRecord("注册账号", u.getId(), -1, u.getName(), u.getEmail());
            }else {
                resultInfo.setMsg("注册失败");
            }
        }else {
            resultInfo.setResult(null);
            resultInfo.setCode(0);
            resultInfo.setMsg("账号或邮箱重复");
        }

        sqlSession.close();
        return resultInfo;
    }

    @Override
    public Integer checkNick(String nick, int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.userSearchByNick(nick, id);
        sqlSession.close();
        return user == null ? 1 : 0;
    }

    @Override
    public ResultInfo<User> updatePwd(HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();

        // 1. 获取参数（昵称、心情）
        String old_pwd = request.getParameter("old_pwd").trim();
        String new_pwd = request.getParameter("new_pwd").trim();

        // 2. 参数的非空校验（判断必填参数非空）
        if (StrUtil.isBlank(new_pwd)) {
            // 如果昵称为空，将状态码和错误信息设置resultInfo对象中，返回resultInfo对象
            resultInfo.setCode(0);
            resultInfo.setMsg("新密码不能为空！");
            return resultInfo;
        }

        // 3. 从session作用域中获取用户对象（获取用户对象中默认的头像）
        User user = (User) request.getSession().getAttribute("user");

        //密码正确
        if (mapper.userSearchByName(user.getName()).getPwd().equals(DigestUtil.md5Hex(old_pwd))){

            int i = mapper.updatePwd(user.getId(), DigestUtil.md5Hex(new_pwd));

            if (i > 0){
                resultInfo.setCode(1);
                resultInfo.setMsg("修改成功");
                //记录
                record.insertRecord("修改密码", user.getId(), -1, "#", "#");
                sqlSession.close();
                return resultInfo;
            }else {
                resultInfo.setCode(0);
                resultInfo.setMsg("修改失败");
                sqlSession.close();
                return resultInfo;
            }

        }else {
            sqlSession.close();
            resultInfo.setCode(0);
            resultInfo.setMsg("密码错误");
            return resultInfo;
        }
    }

    @Override
    public ResultInfo<User> updateUser(HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        // 1. 获取参数（昵称、心情）
        String nick = request.getParameter("nick").trim();
        String mood = request.getParameter("mood").trim();
        String head = "";

        //防止xss注入
        nick = XssStrUtils.replaceHtmlCode(nick);
        mood = XssStrUtils.replaceHtmlCode(mood);


        // 2. 参数的非空校验（判断必填参数非空）
        if (StrUtil.isBlank(nick)) {
            // 如果昵称为空，将状态码和错误信息设置resultInfo对象中，返回resultInfo对象
            resultInfo.setCode(0);
            resultInfo.setMsg("用户昵称不能为空！");
            sqlSession.close();
            return resultInfo;
        }

        if (nick.length() > 30 || mood.length() > 60){
            resultInfo.setCode(0);
            resultInfo.setMsg("昵称不超过30位心情不超过60位！");
            sqlSession.close();
            return resultInfo;
        }

        // 3. 从session作用域中获取用户对象id
        User user = (User) request.getSession().getAttribute("user");
        int id = user.getId();

        // 4. 实现上上传文件
        try {
            // 1. 获取Part对象 request.getPart("name"); name代表的是file文件域的name属性值
            Part part = request.getPart("img");
            // 2. 通过Part对象获取上传文件的文件名 (从头部信息中获取上传的文件名)
            String header = part.getHeader("Content-Disposition");
            // 获取具体的请求头对应的值
            String str = header.substring(header.lastIndexOf("=") + 2);
            // 获取上传的文件名
            String fileName = str.substring(0, str.length() - 1);
            String fileType = null;
            if (fileName != null && fileName.length() > 0){
                fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            }
            // 3. 判断文件名是否为空
            if (!StrUtil.isBlank(fileName) && "jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType)) {
                //修改图片名为唯一标识
                fileName = id + "_" + System.currentTimeMillis() + "_" + fileName;
                head = fileName;

                // 如果用户上传了头像，则更新用户对象中的头像

                // 4. 获取文件存放的路径  WEB-INF/upload/目录中
                String filePath = request.getServletContext().getRealPath("/WEB-INF/upload/");
                // 5. 上传文件到指定目录
                part.write(filePath + "/" + fileName);
            }else {
                head = user.getHead();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 6. 调用Dao层的更新方法，返回受影响的行数
        int row = mapper.updateUser(id, nick, mood, head);
        // 7. 判断受影响的行数
        if (row > 0) {
            resultInfo.setCode(1);
            // 更新session中用户对象
            user = mapper.userSearchByName(user.getName());
            request.getSession().setAttribute("user", user);
        } else {
            resultInfo.setCode(0);
            resultInfo.setMsg("更新失败！");
        }
        sqlSession.close();
        return resultInfo;
    }


    @Override
    public ResultInfo<User> updateEmail(int id, String email) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        //判断邮箱是否重复
        User user = mapper.userSearchByEmail(email);
        if (user == null){
            //邮箱不重复
            int row = mapper.updateEmail(id, email);
            if (row > 0){
                resultInfo.setCode(1);
                User user1 = mapper.userSearchByID(id);
                //记录
                record.insertRecord("修改邮箱", user1.getId(), -1, user1.getEmail(), "#");
                resultInfo.setResult(user1);
                sqlSession.close();
                return resultInfo;
            }else {
                resultInfo.setCode(0);
                User user1 = mapper.userSearchByID(id);
                resultInfo.setResult(user1);
                resultInfo.setMsg("修改失败");
                sqlSession.close();
                return resultInfo;
            }
        }else {
            resultInfo.setCode(0);
            User user1 = mapper.userSearchByID(id);
            resultInfo.setResult(user1);
            resultInfo.setMsg("邮箱冲突");
            sqlSession.close();
            return resultInfo;
        }

    }

    @Override
    public ResultInfo<Integer> updatePwd_forget(String email, String pwd) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);
        //加密
        pwd = DigestUtil.md5Hex(pwd);
        ResultInfo<Integer> resultInfo = new ResultInfo<>();
        int row =mapper.updatePwdByEmail(email, pwd);
        if (row > 0){
            resultInfo.setCode(1);
            //记录
            User user = mapper.userSearchBYNameAndPwd(email, pwd);
            record.insertRecord("找回密码", user.getId(), -1, email, "#");
            resultInfo.setResult(1);
            sqlSession.close();
            return resultInfo;
        }else {
            resultInfo.setCode(0);
            resultInfo.setResult(0);
            resultInfo.setMsg("修改失败");
            sqlSession.close();
            return resultInfo;
        }

    }

    @Override
    public User getUserByName(String name) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = userMapper.userSearchByName(name);
        sqlSession.close();
        return user;
    }

    @Override
    public void updateLoginInfo(int id, String ip) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        userMapper.updateLoginInfo(id, ip);
        sqlSession.close();
    }

    @Override
    public ArrayList<User> getAllUserList() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        ArrayList<User> users = userMapper.getAllUserList();
        sqlSession.close();

        //清空用户密码(我也不知道为啥突然这么写，可能是为了安全)
        for (User user : users) {
            user.setPwd("");
        }

        return users;
    }

    @Override
    public Page<User> getAllUserListByPage(int pageNum) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //查询用户总数
        int count = mapper.getUserCount();

        ArrayList<User> users = mapper.getUserListByPage((pageNum - 1) * 10);
        Page<User> page = new Page<>(pageNum, 10, count);
        page.setDataList(users);
        System.out.println(page);
        sqlSession.close();
        return page;
    }

    @Override
    public ResultInfo<User> deleteUser(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        resultInfo.setResult(null);

        //权限判断
        User user = (User) request.getSession().getAttribute("user");
        User user1 = mapper.userSearchByID(id);

        //权限不足
        if (user.getRole() <= user1.getRole() || user1.getRole() == 3){
            resultInfo.setCode(0);
            resultInfo.setMsg("权限不足");
            sqlSession.close();
            return resultInfo;
        }

        int i = mapper.deleteUser(id);
        if (i > 0){
            resultInfo.setCode(1);

            recordMapper.insertRecord("删除用户", id, -1 , "管理员删除该用户", "管理员ID: " + user.getId());
        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("删除失败");
        }
        sqlSession.close();
        return resultInfo;

    }

    @Override
    public ResultInfo<User> closeUser(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        resultInfo.setResult(null);

        User user1 = mapper.userSearchByID(id);
        User user = (User) request.getSession().getAttribute("user");
        //权限不足
        if (user.getRole() <= user1.getRole() || user1.getRole() == 3){
            resultInfo.setCode(0);
            resultInfo.setMsg("权限不足");
            sqlSession.close();
            return resultInfo;
        }

        int i = mapper.closeUser(id);
        System.out.println("封禁user结果：" + i);
        if (i > 0){
            resultInfo.setCode(1);
            recordMapper.insertRecord("封禁用户", id, -1 , "管理员封禁该用户", "管理员ID: " + user.getId());

        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("封禁失败");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public ResultInfo<User> liveOrOpenUser(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<User> resultInfo = new ResultInfo<>();
        resultInfo.setResult(null);

        User user1 = mapper.userSearchByID(id);
        User user = (User) request.getSession().getAttribute("user");
        //权限不足
        if (user.getRole() <= user1.getRole() || user1.getRole() == 3){
            resultInfo.setCode(0);
            resultInfo.setMsg("权限不足");
            sqlSession.close();
            return resultInfo;
        }

        int i = mapper.liveUser(id);

        if (i > 0){
            resultInfo.setCode(1);
            recordMapper.insertRecord("解封或恢复用户", id, -1 , "管理员解封或恢复该用户", "管理员ID: " + user.getId());

        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("恢复或者解禁失败");
        }
        sqlSession.close();
        return resultInfo;
    }
}
